import React, { memo, useRef, useState } from "react"
import { shallowEqual, useSelector } from "react-redux"

import HeaderWrapper from "./style"
import HeaderCenter from "./c-cpns/header-center"
import HeaderLeft from "./c-cpns/header-left"
import HeaderRight from "./c-cpns/header-right"
import HeaderCenterBottom from "./c-cpns/header-center-bottom"
import useScrollPosition from "@/hooks/useScrollPosition"
import { ThemeProvider } from "styled-components"

const AppHeader = memo(() => {
  // 控制搜索栏的显示
  const [showSearchInfo, setSearchInfo] = useState(false)
  const [index, setIndex] = useState(0)

  const { headerConfig } = useSelector(
    (state) => ({
      headerConfig: state.main.headerConfig,
      // isFixed: state.main.headerConfig.isFixed,
      // topAlpha: state.main.headerConfig.topAlpha,
    }),
    shallowEqual
  )
  const { isFixed, topAlpha } = headerConfig

  function setShow(boolean) {
    setSearchInfo(boolean)
  }

  function bottomIndexHandle(index) {
    setIndex(index)
  }
  // 根据滚动的距离 判断是否关闭搜索框
  const { scrollY } = useScrollPosition()
  // 用 useRef 记录上一次 Y 轴滚动的距离,设置初始值为0
  const prevY = useRef(0)
  // 如果搜索框为关闭状态，记录当前 Y 轴的滚动距离
  if (!showSearchInfo) prevY.current = scrollY
  // 当搜索框处于开启状态，并且 滚动的绝对值 大于40 关闭搜索框，用绝对值 是无论向上或向下滚动都应该满足需求
  if (showSearchInfo && Math.abs(scrollY - prevY.current) > 40)
    setSearchInfo(false)
  // 当在 顶部 的时候 透明度设置为0,根据 topAlpha状态 来改变样式
  const isAlpha = topAlpha && scrollY === 0

  return (
    <ThemeProvider theme={{ isAlpha }}>
      {/* // 由于要将所有的 头部区域 写在同一个页面，所以要将每个区域进行拆分 */}
      <HeaderWrapper fixed={isFixed ? "fixed" : "none"} className="fixed">
        <div className="content">
          <div className="top">
            <HeaderLeft />
            <HeaderCenter
              showSearch={setShow}
              isShow={showSearchInfo || isAlpha}
              bottomIndex={bottomIndexHandle}
            />
            <HeaderRight />
          </div>
          {(showSearchInfo || isAlpha) && (
            <div className="bottom">
              <HeaderCenterBottom
                index={index}
                showSearchInfo={showSearchInfo || isAlpha}
              />
            </div>
          )}
        </div>
        {showSearchInfo && (
          <div className="cover" onClick={(e) => setSearchInfo(false)}></div>
        )}
      </HeaderWrapper>
    </ThemeProvider>
  )
})

export default AppHeader
